// ignore_for_file: use_build_context_synchronously

import 'dart:convert';

import 'package:encrypt_and_decrypt_files/dio_util.dart';
import 'package:encrypt_and_decrypt_files/home_page.dart';
import 'package:encrypt_and_decrypt_files/my/register_page.dart';
import 'package:encrypt_and_decrypt_files/widget/extension.dart';
import 'package:encrypt_and_decrypt_files/widget/theme_provider.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({
    super.key,
  });

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final TextEditingController userNameController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    final themeProvider = Provider.of<ThemeProvider>(context);

    return Scaffold(
      appBar: AppBar(
        backgroundColor: themeProvider.mainColor,
        centerTitle: true,
        title: Text('Login'.t(context)),
      ),
      body: Container(
        padding: const EdgeInsets.symmetric(horizontal: 30),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Card(
              color: themeProvider.mainColor,
              child: Container(
                padding: const EdgeInsets.all(16),
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          'Welcome to Login'.t(context),
                          style: const TextStyle(
                              fontSize: 18, fontWeight: FontWeight.bold),
                        )
                      ],
                    ),
                    const SizedBox(height: 16),
                    TextField(
                      controller: userNameController,
                      decoration: InputDecoration(
                        labelText: 'email:'.t(context),
                        hintText: 'Please input email'.t(context),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                        contentPadding: const EdgeInsets.symmetric(
                          vertical: 12,
                          horizontal: 16,
                        ),
                      ),
                    ),
                    const SizedBox(height: 16),
                    TextField(
                      controller: passwordController,
                      decoration: InputDecoration(
                        labelText: 'password:'.t(context),
                        hintText: 'Please input password'.t(context),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                        contentPadding: const EdgeInsets.symmetric(
                          vertical: 12,
                          horizontal: 16,
                        ),
                        suffixIcon: const Icon(Icons.lock),
                      ),
                      obscureText: true,
                    ),
                    const SizedBox(height: 30),
                    Container(
                      decoration: BoxDecoration(
                        color: themeProvider.mainColor,
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Row(
                        children: [
                          Expanded(
                            child: TextButton(
                              onPressed: login,
                              child: Text(
                                'Login'.t(context),
                                style: const TextStyle(color: Colors.black),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(height: 15),
                    Container(
                      decoration: BoxDecoration(
                        color: themeProvider.mainColor,
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Row(
                        children: [
                          Expanded(
                            child: TextButton(
                              onPressed: () {
                                Navigator.push(context,
                                    MaterialPageRoute(builder: (_) {
                                  return const RegisterPage();
                                }));
                              },
                              child: Text(
                                'Go to Register'.t(context),
                                style: const TextStyle(color: Colors.black),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> login() async {
    const url = '/login';
    if (userNameController.text.isEmpty) {
      Fluttertoast.showToast(msg: 'Please enter your email');
      return;
    }
    if (passwordController.text.isEmpty) {
      Fluttertoast.showToast(msg: 'Please enter your password');
      return;
    }

    var params = {
      'email': userNameController.text,
      'password': passwordController.text,
    };
    var response = await DioHttp.of(context).post(url, params, '');

    var resString = json.decode(response.toString());
    if (resString['code'] == 200) {
      SpUtil.putString('token', resString['data']['access_token'] ?? '');
      SpUtil.putObject(
          'userModel',
          UserModel(
            email: userNameController.text,
            password: passwordController.text,
            userId: resString['data']['user_id'],
            memberType: resString['data']['memberType'],
          ));
      Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) {
        return const HomePage();
      }));
    }
    Fluttertoast.showToast(msg: resString['msg']);
  }
}
